package com.reactnativenavigation.controllers;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import com.easemob.helpdesk.activity.MainActivity;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReadableMap;
import com.housekeeperapp.MainApplication;
import com.housekeeperapp.activity.BaseActivity;
import com.reactnativenavigation.NavigationApplication;
import com.reactnativenavigation.bridge.BundleConverter;
import com.reactnativenavigation.params.ActivityParams;
import com.reactnativenavigation.params.AppStyle;
import com.reactnativenavigation.params.ContextualMenuParams;
import com.reactnativenavigation.params.FabParams;
import com.reactnativenavigation.params.LightBoxParams;
import com.reactnativenavigation.params.ScreenParams;
import com.reactnativenavigation.params.SlidingOverlayParams;
import com.reactnativenavigation.params.SnackbarParams;
import com.reactnativenavigation.params.TitleBarButtonParams;
import com.reactnativenavigation.params.TitleBarLeftButtonParams;
import com.reactnativenavigation.params.parsers.ActivityParamsParser;
import com.reactnativenavigation.params.parsers.ScreenParamsParser;
import com.reactnativenavigation.utils.CommonUtils;
import com.reactnativenavigation.utils.OrientationHelper;
import com.reactnativenavigation.views.SideMenu.Side;

import java.util.ArrayList;
import java.util.List;

public class NavigationCommandsHandler {

    private static final String ACTIVITY_PARAMS_BUNDLE = "ACTIVITY_PARAMS_BUNDLE";
    private static final String ACTIVITY_PARAMS_BUNDLE_PAGE = "ACTIVITY_PARAMS_BUNDLE_PAGE";
    private static final String ACTIVITY_PARAMS_APPSTYLE = "ACTIVITY_PARAMS_APPSTYLE";

    public static Bundle saveParams;

    public static Activity mActivity;

    static ActivityParams parseActivityParams(Intent intent) {
        return ActivityParamsParser.parse(intent.getBundleExtra(NavigationCommandsHandler.ACTIVITY_PARAMS_BUNDLE));
    }

    public static ActivityParams parseActivityPageParams(Intent intent) {
        return ActivityParamsParser.parsePage(intent.getBundleExtra(NavigationCommandsHandler.ACTIVITY_PARAMS_BUNDLE_PAGE));
    }

    public static List<ActivityParams> paramsActivityTabs(Intent intent){

        Bundle params = intent.getBundleExtra(NavigationCommandsHandler.ACTIVITY_PARAMS_BUNDLE_PAGE);
        List<ActivityParams> res = new ArrayList<>();

        AppStyle.setAppStyle(params);

        Bundle tabParams = params.getBundle("tabs");
        for (String key : tabParams.keySet()) {
            ScreenParams param = ScreenParamsParser.parse(tabParams.getBundle(key));

            ActivityParams result = new ActivityParams();
            result.type = ActivityParams.Type.SingleScreen;
            result.screenParams = param;

            res.add(result);

        }

        return res;

    }

    /**
     * start a new activity with CLEAR_TASK | NEW_TASK
     *
     * @param params ActivityParams as bundle
     */
    // 特别处理, 从MainActivity进入
    public static void startApp(final Bundle params) {
        if(params.containsKey("tabs")){
            Intent intent = new Intent(MainActivity.instance, NavigationActivity.class);
            IntentDataHandler.onStartApp(intent);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra(ACTIVITY_PARAMS_BUNDLE, params);
//            saveParams = params;
            MainActivity.instance.startActivity(intent);
        }else{//第一次启动
            if(MainActivity.instance != null){// 退出时,走这个逻辑
                if(NavigationActivity.currentActivity != null){
                    NavigationActivity.currentActivity.finish();
                }

                MainActivity.instance.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent(MainActivity.instance, NavigationActivity.class);
                        IntentDataHandler.onStartApp(intent);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.putExtra(ACTIVITY_PARAMS_BUNDLE, params);
                        MainActivity.instance.startActivity(intent);

//                        MainActivity.instance.finish();
                    }
                });

                return;
            }

            Activity activity = com.housekeeperapp.MainActivity.getInstance();
            Intent intent = new Intent(activity, NavigationActivity.class);
            IntentDataHandler.onStartApp(intent);

            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra(ACTIVITY_PARAMS_BUNDLE, params);
//            saveParams = params;
            activity.startActivity(intent);
//            activity.finish();
        }

    }

    /**
     * start main activity
     *
     * @param params ActivityParams as bundle
     */
    public static void startMainActivityApp(ReadableMap params){
//        Bundle bundle = BundleConverter.toBundle(params.getArray("tabs"));

        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);

        intent.putExtra("user_id", params.getInt("user_id"));
        intent.putExtra("user_role", params.getInt("user_role"));
        intent.putExtra("ticket", params.getString("ticket"));
        intent.putExtra("easemob_kefu_name", params.getString("easemob_kefu_name"));
        intent.putExtra("easemob_kefu_pwd", params.getString("easemob_kefu_pwd"));
        intent.putExtra("skill_group",params.getString("skill_group"));
        intent.putExtra("productKey",params.getString("productKey"));
        intent.putExtra("village",params.getString("village"));

        intent.putExtra(ACTIVITY_PARAMS_BUNDLE_PAGE, BundleConverter.toBundle(params));
//        intent.putExtra(ACTIVITY_PARAMS_APPSTYLE, BundleConverter.toBundle(params));
        if(!MainApplication.getInstance().isNoActivity()){
            Activity activity = MainApplication.getInstance().getTopActivity();
            intent.setClass(activity, MainActivity.class);
            activity.startActivity(intent);
        }
    }

    public static void push(final Bundle screenParams) {
//        final NavigationActivity currentActivity = NavigationActivity.currentActivity;
//        if (currentActivity == null) {
//            return;
//        }

        final ScreenParams params = ScreenParamsParser.parse(screenParams);

        NavigationApplication.instance.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                String classname = params.screenId.replace("housekeeperapp.","");

                try {
                    Class clazz = Class.forName("com.housekeeperapp.activity." + CommonUtils.captureName(classname));
                    Intent intent = new Intent(MainApplication.getInstance().getTopActivity(), clazz);
                    intent.putExtra(ACTIVITY_PARAMS_BUNDLE_PAGE, screenParams);
                    MainApplication.getInstance().getTopActivity().startActivity(intent);

                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }


//                currentActivity.push(params);
            }
        });
    }

    public static void pop(Bundle screenParams) {
//        final NavigationActivity currentActivity = NavigationActivity.currentActivity;
//        if (currentActivity == null) {
//            return;
//        }

        final ScreenParams params = ScreenParamsParser.parse(screenParams);
        NavigationApplication.instance.runOnMainThread(new Runnable() {
            @Override
            public void run() {

                if(mActivity != null && mActivity.isDestroyed()){
                    mActivity = null;
                }

                if (mActivity != null && mActivity.isFinishing()) {
                    return;
                }

                mActivity = MainApplication.getInstance().getTopActivity();
                if(!(mActivity instanceof MainActivity)){
                    mActivity.finish();
                }

            }
        });
    }

    public static void popToRoot(Bundle screenParams) {
        final NavigationActivity currentActivity = NavigationActivity.currentActivity;
        if (currentActivity == null) {
            return;
        }

        final ScreenParams params = ScreenParamsParser.parse(screenParams);
        NavigationApplication.instance.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                currentActivity.popToRoot(params);
            }
        });
    }

    public static void newStack(Bundle screenParams) {
        final NavigationActivity currentActivity = NavigationActivity.currentActivity;
        if (currentActivity == null) {
            return;
        }

        final ScreenParams params = ScreenParamsParser.parse(screenParams);
        NavigationApplication.instance.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                currentActivity.newStack(params);
            }
        });
    }

    public static void setTopBarVisible(final String screenInstanceID, final boolean hidden, final boolean animated) {
        final NavigationActivity currentActivity = NavigationActivity.currentActivity;
        if (currentActivity == null) {
            return;
        }

        NavigationApplication.instance.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                currentActivity.setTopBarVisible(screenInstanceID, hidden, animated);
            }
        });
    }

    public static void setBottomTabsVisible(final boolean hidden, final boolean animated) {
        final NavigationActivity currentActivity = NavigationActivity.currentActivity;
        if (currentActivity == null) {
            return;
        }

        NavigationApplication.instance.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                currentActivity.setBottomTabsVisible(hidden, animated);
            }
        });
    }

    public static void setScreenTitleBarTitle(final String screenInstanceId, final String title) {
        final NavigationActivity currentActivity = NavigationActivity.currentActivity;
        if (currentActivity == null) {
            return;
        }

        NavigationApplication.instance.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                currentActivity.setTitleBarTitle(screenInstanceId, title);
            }
        });
    }

    public static void setScreenTitleBarSubtitle(final String screenInstanceId, final String subtitle) {
        final NavigationActivity currentActivity = NavigationActivity.currentActivity;
        if (currentActivity == null) {
            return;
        }

        NavigationApplication.instance.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                currentActivity.setTitleBarSubtitle(screenInstanceId, subtitle);
            }
        });
    }

    public static void showModal(final Bundle params) {
        final NavigationActivity currentActivity = NavigationActivity.currentActivity;
        if (currentActivity == null) {
            return;
        }

        NavigationApplication.instance.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                currentActivity.showModal(ScreenParamsParser.parse(params));
            }
        });
    }

    public static void showLightBox(final LightBoxParams params) {
        final NavigationActivity currentActivity = NavigationActivity.currentActivity;
        if (currentActivity == null) {
            return;
        }

        NavigationApplication.instance.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                currentActivity.showLightBox(params);
            }
        });
    }

    public static void dismissLightBox() {
        final NavigationActivity currentActivity = NavigationActivity.currentActivity;
        if (currentActivity == null) {
            return;
        }

        NavigationApplication.instance.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                currentActivity.dismissLightBox();
            }
        });
    }

    public static void setScreenTitleBarRightButtons(final String screenInstanceId,
                                                     final String navigatorEventId,
                                                     final List<TitleBarButtonParams> titleBarButtons) {
//        final NavigationActivity currentActivity = NavigationActivity.currentActivity;
//        if (currentActivity == null) {
//            return;
//        }


        NavigationApplication.instance.runOnMainThread(new Runnable() {
            @Override
            public void run() {

                List<Activity> list = MainApplication.getInstance().getActivityList();

                for (Activity activity : list) {
                    if (activity != null) {
                        if (!activity.isFinishing() && activity instanceof BaseActivity) {
                            BaseActivity base = (BaseActivity) activity;
                            if(!CommonUtils.isBlank(base.screenId) && base.screenId.equals(screenInstanceId)){
                                base.getLayout().setTitleBarRightButtons(screenInstanceId, navigatorEventId, titleBarButtons);
                                break;
                            }
                        }
                    }
                }

            }
        });
    }

    public static void setScreenTitleBarLeftButtons(final String screenInstanceId,
                                                    final String navigatorEventId,
                                                    final TitleBarLeftButtonParams titleBarButtons) {
        final NavigationActivity currentActivity = NavigationActivity.currentActivity;
        if (currentActivity == null) {
            return;
        }

        NavigationApplication.instance.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                currentActivity.setTitleBarLeftButton(screenInstanceId, navigatorEventId, titleBarButtons);
            }
        });
    }

    public static void setScreenFab(final String screenInstanceId, final String navigatorEventId, final FabParams fab) {
        final NavigationActivity currentActivity = NavigationActivity.currentActivity;
        if (currentActivity == null) {
            return;
        }
        NavigationApplication.instance.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                currentActivity.setScreenFab(screenInstanceId, navigatorEventId, fab);
            }
        });
    }

    public static void dismissTopModal() {
        final NavigationActivity currentActivity = NavigationActivity.currentActivity;
        if (currentActivity == null) {
            return;
        }

        NavigationApplication.instance.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                currentActivity.dismissTopModal();
            }
        });
    }

    public static void dismissAllModals() {
        final NavigationActivity currentActivity = NavigationActivity.currentActivity;
        if (currentActivity == null) {
            return;
        }

        NavigationApplication.instance.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                currentActivity.dismissAllModals();
            }
        });
    }

    public static void toggleSideMenuVisible(final boolean animated, final Side side) {
        final NavigationActivity currentActivity = NavigationActivity.currentActivity;
        if (currentActivity == null) {
            return;
        }

        NavigationApplication.instance.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                currentActivity.toggleSideMenuVisible(animated, side);
            }
        });
    }

    public static void setSideMenuVisible(final boolean animated, final boolean visible, final Side side) {
        final NavigationActivity currentActivity = NavigationActivity.currentActivity;
        if (currentActivity == null) {
            return;
        }

        NavigationApplication.instance.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                currentActivity.setSideMenuVisible(animated, visible, side);
            }
        });
    }

    public static void selectBottomTabByTabIndex(final Integer index) {
//        final NavigationActivity currentActivity = NavigationActivity.currentActivity;
//        if (currentActivity == null) {
//            return;
//        }

        NavigationApplication.instance.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                MainActivity.instance.selectTab(index);
//                currentActivity.selectBottomTabByTabIndex(index);
            }
        });
    }

    public static void selectBottomTabByNavigatorId(final String navigatorId) {
        final NavigationActivity currentActivity = NavigationActivity.currentActivity;
        if (currentActivity == null) {
            return;
        }

        NavigationApplication.instance.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                currentActivity.selectBottomTabByNavigatorId(navigatorId);
            }
        });
    }

    public static void setBottomTabBadgeByIndex(final Integer index, final String badge) {
        final NavigationActivity currentActivity = NavigationActivity.currentActivity;
        if (currentActivity == null) {
            return;
        }

        NavigationApplication.instance.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                currentActivity.setBottomTabBadgeByIndex(index, badge);
            }
        });
    }

    public static void setBottomTabBadgeByNavigatorId(final String navigatorId, final String badge) {
        final NavigationActivity currentActivity = NavigationActivity.currentActivity;
        if (currentActivity == null) {
            return;
        }

        NavigationApplication.instance.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                currentActivity.setBottomTabBadgeByNavigatorId(navigatorId, badge);
            }
        });
    }

    public static void showSlidingOverlay(final SlidingOverlayParams params) {
        final NavigationActivity currentActivity = NavigationActivity.currentActivity;
        if (currentActivity == null) {
            return;
        }

        NavigationApplication.instance.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                currentActivity.showSlidingOverlay(params);
            }
        });
    }

    public static void hideSlidingOverlay() {
        final NavigationActivity currentActivity = NavigationActivity.currentActivity;
        if (currentActivity == null) {
            return;
        }

        NavigationApplication.instance.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                currentActivity.hideSlidingOverlay();
            }
        });
    }

    public static void showSnackbar(final SnackbarParams params) {
        final NavigationActivity currentActivity = NavigationActivity.currentActivity;
        if (currentActivity == null) {
            return;
        }

        NavigationApplication.instance.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                currentActivity.showSnackbar(params);
            }
        });
    }

    public static void showContextualMenu(final String screenInstanceId, final ContextualMenuParams params, final Callback onButtonClicked) {
        final NavigationActivity currentActivity = NavigationActivity.currentActivity;
        if (currentActivity == null) {
            return;
        }

        NavigationApplication.instance.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                currentActivity.showContextualMenu(screenInstanceId, params, onButtonClicked);
            }
        });
    }

    public static void dismissContextualMenu(final String screenInstanceId) {
        final NavigationActivity currentActivity = NavigationActivity.currentActivity;
        if (currentActivity == null) {
            return;
        }

        NavigationApplication.instance.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                currentActivity.dismissContextualMenu(screenInstanceId);
            }
        });
    }

    public static void dismissSnackbar() {
        final NavigationActivity currentActivity = NavigationActivity.currentActivity;
        if (currentActivity == null) {
            return;
        }

        NavigationApplication.instance.runOnMainThread(new Runnable() {
            @Override
            public void run() {
                currentActivity.dismissSnackbar();
            }
        });
    }

    public static void getOrientation(Promise promise) {
        final NavigationActivity currentActivity = NavigationActivity.currentActivity;
        if (currentActivity == null) {
            return;
        }
        promise.resolve(OrientationHelper.getOrientation(currentActivity));
    }
}
